import axios from "axios";

const BASE_URL = "http://localhost:8101/api"

const requests = axios.create({
  baseURL: BASE_URL,
  timeout: 5000
})

// interface ApiResponse<T> {
//   code: number;
//   msg: string;
//   data: T;
// }

requests.interceptors.request.use((config) => {
  // const token = localStorage.getItem('token');
  // config.headers.token = token
  // TODO: 请求业务处理
  return config;
}, (error) => {
  return Promise.reject(error);
});

requests.interceptors.response.use((response) => {
  // TODO: 响应业务处理
  
  return response.data
}, (error) => {
  return Promise.reject(error);
});

// get 请求封装
const get = (url: string, params: any) => {
  return new Promise((resolve, reject) => {
    requests({
      url: url,
      method: 'get',
      params: params,
      headers: { 'Content-Type': 'application/json', 'request-ajax': true }
    }).then(response => {
      resolve(response);
    }).catch(error => {
      reject(error);
    });
  });
}

// post 请求封装
const post = (url: string, params: any) => {
  return new Promise((resolve, reject) => {
    requests({
      url: url,
      method: 'post',
      data: params,
      headers: { 'Content-Type': 'application/json', 'request-ajax': true }
    }).then(response => {
      resolve(response);
    }).catch(error => {
      reject(error);
    });
  });
}
// post 请求封装
const fileUpload = (url: string, params: any) => {
  return new Promise((resolve, reject) => {
    requests({
      url: url,
      method: 'post',
      data: params,
      headers: { 'Content-Type': 'multipart/form-data' }
    }).then(response => {
      resolve(response);
    }).catch(error => {
      reject(error);
    });
  });
}

// 文件下载 请求封装
const downloadUrl = (url: string, params: any) => {
  return new Promise((resolve, reject) => {
    requests({
      url: url,
      method: 'post',
      data: params,
      responseType: "blob"
    }).then(response => {
      resolve(response);
    }).catch(error => {
      reject(error);
    });
  });
}

export { post, get, fileUpload, downloadUrl }

export default requests